﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Net.Http.Headers;

namespace MyCompany.MyProject.WebApi.Controllers
{
    /// <summary>
    /// 大文件上传案例
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class UploadController : ControllerBase
    {
        // 上传文件夹路径
        private readonly string _uploadsFolder;
        /// <summary>
        /// 构造函数
        /// </summary>
        public UploadController()
        {
            // 配置上传文件夹为当前目录下的 "Uploads" 文件夹
            _uploadsFolder = Path.Combine(Directory.GetCurrentDirectory(), "Uploads");
            // 如果文件夹不存在则创建
            if (!Directory.Exists(_uploadsFolder)) Directory.CreateDirectory(_uploadsFolder);
        }
        /// <summary>
        /// 处理进度查询
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Process(string fileName)
        {
            try
            {
                fileName = Path.GetFileName(fileName);
                var filePath = Path.Combine(_uploadsFolder, fileName);

                if (System.IO.File.Exists(filePath))
                {
                    var fileInfo = new FileInfo(filePath);
                    return Ok(new { fileSize = fileInfo.Length });
                }
                else
                {
                    return NotFound();
                }
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = $"获取进度失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 上传文件接口
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Upload()
        {
            try
            {
                // 检查请求是否为 multipart 格式
                if (!Request.HasFormContentType)
                {
                    return BadRequest("请求格式不是有效的 multipart/form-data");
                }

                var form = await Request.ReadFormAsync();

                // 获取文件信息
                var file = form.Files["file"];
                if (file == null || file.Length == 0)
                {
                    return BadRequest("未上传文件");
                }

                // 获取文件名和总大小
                var fileName = form["fileName"].FirstOrDefault() ?? ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                var totalSize = long.Parse(form["totalSize"].FirstOrDefault() ?? "0");
                var startByte = long.Parse(form["startByte"].FirstOrDefault() ?? "0");

                // 确保文件名安全
                fileName = Path.GetFileName(fileName);
                var filePath = Path.Combine(_uploadsFolder, fileName);

                // 写入文件块
                using (var stream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    stream.Seek(startByte, SeekOrigin.Begin);
                    await file.CopyToAsync(stream);
                }

                // 检查文件是否已全部上传
                var currentFileSize = new FileInfo(filePath).Length;
                var isComplete = currentFileSize >= totalSize;

                if (isComplete)
                {
                    // 可选：验证文件完整性
                    // 这里可以添加文件哈希验证代码

                    return Ok(new { message = "上传完成", fileSize = currentFileSize });
                }
                else
                {
                    return Ok(new { message = "上传中", bytesWritten = file.Length, totalSize });
                }
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = $"上传失败: {ex.Message}" });
            }
        }
    }
}
